package com.winit.core.mq.queue.impl;

import com.winit.core.mq.listener.QueueListener;
import com.winit.core.mq.message.Message;
import com.winit.core.mq.queue.MessageQueue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created by xiangyu.liang on 2016/8/15.
 */
public class UnsyncMessageQueue implements MessageQueue {
    private String name;
    //private BlockingQueue<Message> queue;
    private List<QueueListener> listeners;
    private Long expireTime;
    private static Long DEFAULT_TIME=86400000L;

    @Override
    public boolean hasListener() {
        return this.listeners.size()>0;
    }

    public UnsyncMessageQueue(String name){
        this.name=name;
        //this.queue=new LinkedBlockingQueue<>(500);
        this.listeners =new ArrayList<>();
        this.expireTime=System.currentTimeMillis()+DEFAULT_TIME;
    }
    @Override
    public void destroy() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public boolean enqueue(Message message) {
        try {
            for(QueueListener listener: listeners){
                listener.onMessage(message);
            }
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @Override
    public void addListener(QueueListener listener) {
        this.listeners.add(listener);
    }

    @Override
    public void removeListener(Object object) {
        int i=listeners.size()-1;
        for(;i>=0;i--){
            QueueListener listener=listeners.get(i);
            if(listener.equals(object)){
                listeners.remove(i);
            }
        }
    }
}
